package com.carl.zeus.web.system;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.plugins.Page;
import com.carl.zeus.common.annotation.Log;
import com.carl.zeus.common.base.BaseController;
import com.carl.zeus.common.constant.BusinessCode;
import com.carl.zeus.common.constant.BusinessMsg;
import com.carl.zeus.common.util.BusinessMsgUtil;
import com.carl.zeus.model.system.SysUser;
import com.carl.zeus.model.vo.CustomPage;
import com.carl.zeus.model.vo.FrontPage;
import com.carl.zeus.model.vo.UserOnlineBo;
import com.carl.zeus.server.system.SysRoleService;
import com.carl.zeus.server.system.SysUserService;
import com.carl.zeus.util.MyDES;
import org.apache.commons.lang3.StringUtils;
import org.crazycake.shiro.RedisSessionDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author zcm
 * @since 2017-03-11
 */
@Controller
@RequestMapping(value = "sys/user")
public class UserController extends BaseController{

	@Autowired
	private SysUserService sysUserService;

	@Autowired
	private SysRoleService sysRoleService;

	/**
	 * 跳转到用户列表
	 * @return
	 */
	@Log("用户列表")
	@RequestMapping(value = "list", method = RequestMethod.GET)
	public String list() {
		return "system/user";
	}

	/**
	 * 分页 -- 用户列表
	 * @param page
	 * @param limit
	 * @return
	 */
	@RequestMapping(value = "listAjax", method = RequestMethod.POST)
	@ResponseBody
	public String listAjax(@RequestParam(value = "page", defaultValue = "1") int page,
						   @RequestParam(value = "limit", defaultValue = "10") int limit,
						   @RequestParam(value = "key", defaultValue = "") String key,
						   @RequestParam(value = "value", defaultValue = "") String value) {
		Map<String, Object> map = new HashMap<>();
		List<SysUser> userList = sysUserService.listAjax(page, limit, key, value);
		map.put("code",0);
		map.put("msg","");
		map.put("count", sysUserService.countUserList());
		map.put("data", userList);
		return JSON.toJSONString(map);
	}

	/**
	 * 新增用户
	 * @param model
	 * @return
	 */
	@Log("新增用户")
	@RequestMapping(value = "add", method = RequestMethod.GET)
	public String add(Model model) {
		model.addAttribute("user", new SysUser());
		return "system/user-edit";
	}

	/**
	 * 跳转到用户编辑页
	 * @param id
	 * @param model
	 * @return
	 */
	@Log("编辑用户")
	@RequestMapping(value = "edit/{id}", method = RequestMethod.GET)
	public String edit(@PathVariable("id") Long id, Model model) {
		if (id != null) {
			SysUser user = sysUserService.selectById(id);
			model.addAttribute("user", user);
		}
		return "system/user-edit";
	}

	// 增加和修改
	@Log("保存用户")
	@RequestMapping(value = "save", method = RequestMethod.POST)
	@ResponseBody
	public BusinessMsg edit(SysUser user) {
		if (StringUtils.isNotEmpty(user.getPassword()) && StringUtils.isNotEmpty(user.getUsername())) {
			// 创建用户
			user.setPassword(MyDES.encryptBasedDes(user.getPassword() + user.getUsername()));
			user.setCreateTime(new Date());
		}
		user.setLastUpdateTime(new Date());
		sysUserService.insertOrUpdate(user);
		return BusinessMsgUtil.returnCodeMessage(BusinessCode.GLOBAL_SUCCESS);
	}

	// 跳转到在线用户管理页面
	@Log("在线用户列表")
	@RequestMapping(value = "online", method = RequestMethod.GET)
	public String onlineUser() {
		return "system/user-online";
	}

	// 在线用户列表json
	@RequestMapping(value = "onlineAjax", method = RequestMethod.GET)
	@ResponseBody
	public String OnlineUsers(@RequestParam(value = "page", defaultValue = "1") int page,
							  @RequestParam(value = "limit", defaultValue = "10") int limit) {
		Map<String, Object> map = new HashMap<>();
		List<UserOnlineBo> userList = sysUserService.getUserOnline(page, limit);
		map.put("code", 0);
		map.put("msg", "");
		map.put("count", sysUserService.getUserOnlineSize());
		map.put("data", userList);
		return JSON.toJSONString(map);
	}

	/**
	 * 跳转到用户角色分配页面
	 * @param userId 用户Id
	 * @return
	 */
	@Log("分配角色")
	@RequestMapping(value = "/grant/{id}", method = RequestMethod.GET)
	public String userGrantPage(@PathVariable("id") Long userId, Model model){
		SysUser user = sysUserService.selectUserRolesByUserId(userId);
		model.addAttribute("user", user);
		return "system/user-grant";
	}

	// 强制踢出用户
	@Log("踢出用户")
	@RequestMapping(value = "kickout")
	@ResponseBody
	public String kickout(@RequestParam(value = "ids[]") String[] ids) {
		Map<String, Object> resultMap = new HashMap<>();
		try {
			for (String sessionId : ids) {
				sysUserService.kickout(sessionId);
			}
			resultMap.put("flag", true);
			resultMap.put("msg", "强制踢出成功！");
		} catch (Exception e) {
			resultMap.put("flag", false);
			resultMap.put("msg", e.getMessage().toString());
		}
		return JSON.toJSONString(resultMap);
	}

	/**
	 * 查询待分配的角色信息(用以给用户分配角色时显示)
	 * @param  roleIds 已分配角色Id
	 */
	@RequestMapping(value = "undistributedRoleList", method = RequestMethod.POST)
	@ResponseBody
	public String ajaxUndistributedRoleList(String roleIds){
		return sysRoleService.selectUserRoleByRoleIdList(roleIds);
	}

	/**
	 * 查询状态为有效,已分配的角色信息(用已用户分配角色显示)
	 * @param roleIds 已分配角色Id
	 */
	@RequestMapping(value = "deceasedRoleList", method = RequestMethod.POST)
	@ResponseBody
	public String ajaxDeceasedRoleList(String roleIds){
		return sysRoleService.selectDeceasedUserRoleByRoleIdList(roleIds);
	}

	/**
	 * 保存用户分配角色信息
	 * @param userId 用户Id
	 * @param roleIds 分配的角色信息
	 * @return
	 */
	@RequestMapping(value = "saveUserRole", method = RequestMethod.POST)
	@ResponseBody
	public BusinessMsg ajaxSaveUserRole(Long userId, String roleIds){
		try {
			return sysRoleService.saveUserRole(userId, roleIds);
		} catch (Exception e) {
			return BusinessMsgUtil.returnCodeMessage(BusinessCode.USER_ROLE_SAVE_ERROR);
		}
	}

	/**
	 * 失效用户
	 * @param userId 用户Id
	 * @return
	 */
	@Log("失效用户")
	@RequestMapping(value = "fail", method = RequestMethod.POST)
	@ResponseBody
	public BusinessMsg ajaxUserFail(Long userId){
		try {
			return sysUserService.updateUserStatus(userId);
		} catch (Exception e) {
			return BusinessMsgUtil.returnCodeMessage(BusinessCode.USER_FAIL_ERROR);
		}
	}

	/**
	 * 批量失效用户
	 * @param userIds 用户Id
	 * @return
	 */
	@Log("批量失效用户")
	@RequestMapping(value = "batchFail", method = RequestMethod.POST)
	@ResponseBody
	public BusinessMsg ajaxUserBatchFail(@RequestParam(value = "userIds[]") Long[] userIds){
		try {
			return sysUserService.updateUserBatchStatus(userIds);
		} catch (Exception e) {
			return BusinessMsgUtil.returnCodeMessage(BusinessCode.USER_FAIL_ERROR);
		}
	}

	/**
	 * 用户信息
	 * @param id
	 * @param model
	 * @return
	 */
	@Log("用户信息")
	@RequestMapping(value = "info/{id}", method = RequestMethod.GET)
	public String  info(@PathVariable("id") Long id, Model model) {
		SysUser user = sysUserService.selectById(id);
		model.addAttribute("user", user);
		return "user-info";
	}

	@Log("修改用户密码")
	@RequestMapping(value = "rePassword", method = RequestMethod.POST)
	public BusinessMsg rePassword() {
		return null;
	}

	/**
	 * 解锁屏幕
	 * @param userId
	 * @param password
	 * @return
	 */
	@Log("解锁屏幕")
	@RequestMapping(value = "unLock", method = RequestMethod.POST)
	@ResponseBody
	public BusinessMsg unLock(Long userId, String password) {
		if (userId != null && StringUtils.isNotEmpty(password)) {
			SysUser user = sysUserService.selectById(userId);
			String rePassword = MyDES.encryptBasedDes(password + user.getUsername());
			if (user.getPassword().equals(rePassword)) {
				return BusinessMsgUtil.returnCodeMessage(BusinessCode.GLOBAL_SUCCESS);
			}
		}
		return BusinessMsgUtil.returnCodeMessage(BusinessCode.GLOBAL_ERROR);
	}

}
